<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use think\Request;
use Mpdf\Mpdf;

/**
 * 计算返佣生效时间
 */
function calculateRemainingHoursWithBatch($endTime) {
    
    $delaySeconds = config("DELAY_REBATE_TIME"); // 7天的秒数
    $effectiveTime = strtotime($endTime) + $delaySeconds; // 理论生效时间
    
    // 获取当前时间
    $currentTime = time();
    
    // 如果已经过了理论生效时间
    if ($currentTime >= $effectiveTime) {
        // 计算下一个批量更新时间（今天或明天的00:05）
        $nextBatchTime = strtotime('today 00:05:00');
        if ($currentTime > $nextBatchTime) {
            $nextBatchTime = strtotime('tomorrow 00:05:00');
        }
        
        // 如果下一个批量更新时间已过，说明已生效
        if ($currentTime >= $nextBatchTime) {
            return 0;
        }
        
        // 返回距离下一个批量更新的小时数
        $remainingSeconds = $nextBatchTime - $currentTime;
        return ceil($remainingSeconds / 3600);
    }
    
    // 如果还未到理论生效时间
    // 计算理论生效后的第一个批量更新时间
    $effectiveDate = date('Y-m-d', $effectiveTime);
    $firstBatchAfterEffective = strtotime($effectiveDate . ' 00:05:00');
    
    // 如果理论生效时间在00:05之后，则批量更新在第二天
    if ($effectiveTime > $firstBatchAfterEffective) {
        $firstBatchAfterEffective = strtotime('next day 00:05:00', $firstBatchAfterEffective);
    }
    
    // 计算剩余时间
    $remainingSeconds = $firstBatchAfterEffective - $currentTime;
    
    // 如果剩余时间为负，说明已生效
    if ($remainingSeconds <= 0) {
        return 0;
    }
    
    return ceil($remainingSeconds / 3600);
}

/**
 * 生成昵称
 */
function maskString($str){
	$len = strlen($str);
	$first = substr($str, 0, 3);
	$last = substr($str, -4);
	$midLength = $len - 3 -4;
	
	$str = '';
	for ($i=0; $i < $midLength; $i++) { 
		$str .= '*';
	}
	return $first.$str.$last;
}

/**
 * xml转数组
 */
function xmlToArray($xml){
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}

/**
 * 获取本月起始日期
 */
function getThisMonthDate(){
	$satartDate = date("Y-m-01 00:00:00");
	$endDate = date("Y-m-t 23:59:59");
	return [$satartDate, $endDate];
}

/**
 * 校验收案时间是否小于当前日期
 */
function checkReceivetime($receivetime){
	$receivetime = strtotime(date("Y-m-d", strtotime($receivetime)));
	$time = strtotime(date("Y-m-d", time()));
	if( $receivetime < $time || $receivetime == $time ){
		return TRUE;
	}else{
		return FALSE;
	}
}

/**
 * 验证日期
 */
function isValidDate($date, $format = 'Y-m-d') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) === $date;
}

/**
 * 用户名打星
 */
function maskName($fullName, $maskChar = '*', $keepCount = 1) {
    $names = explode(' ', $fullName);
    if (count($names) > 1) {
        $names[1] = str_repeat($maskChar, strlen($names[1]) - $keepCount) . substr($names[1], -$keepCount);
    }
    return implode(' ', $names);
}

/**
 * 获取指定年月最后一天
 */
function getLastDayOfMonth($year, $month) {
    return date('Y-m-t', strtotime("$year-$month"));
}

// 应用公共文件

function getMillisecond() {

list($microsecond , $time) = explode(' ', microtime()); //' '中间是一个空格

return (float)sprintf('%.0f',(floatval($microsecond)+floatval($time))*1000);

}

/**
* 获取两个日期的区间,返回年月日周期数组
*/
function getDateList2($startDate, $endData){
$startTime = strtotime($startDate);
$endTime = strtotime($endData);
$arr = [];
while ($startTime <= $endTime) {
$arr[] = date("Y-m-d", $startTime);
$startTime = strtotime('+1 day', $startTime);
}
return $arr;
}
                        

/**
* 获取两个日期的区间,返回年月周期数组
*/
function getDateList($startDate, $endData){
$startTime = strtotime($startDate);
$endTime = strtotime($endData);
$arr = [];
while ($startTime <= $endTime) {
$arr[] = date("Y-m", $startTime);
$startTime = strtotime('+1 day', $startTime);
}
return $arr;
}

/**
* 提取字符串中的数字
*/
function getStrInt($str){
// 使用正则表达式提取数字
preg_match_all('/\d+/', $str, $matches);

// 输出提取的数字
$data = [];
foreach ($matches[0] as $match) {
$data[] = $match;
}
return $data;
}

/**
* 转换日期格式
*/
function convertDate($date){

if( strpos($date, '/') ) $date = date("Y-m-d H:i:s", strtotime($date));
if( strpos($date, '年') ) $date = str_replace("年","-",$date);
if( strpos($date, '月') ) $date = str_replace("月","-",$date);
if( strpos($date, '日') ) $date = str_replace("日","",$date);
if( !strtotime($date) || strpos($date, '.') ) {
$date = floatval($date);
$date = gmdate('Y-m-d', ($date - 25569) * 86400);
}
return $date;
}

/**
* 获取随机字符串
*/
function getRandStr($length = 4){
$rand = [
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
];

$l = count($rand) -1;
$str = [];
for ($i=0; $i < $length; $i++) {
$str[] = $rand[rand(0, $l)];
}
return implode('', $str);
}

if (!function_exists('htmlToPdf')) {
/**
*
* @param
*/
function htmlToPdf($html = '', $title = "标题", $fileName = ""){

$mpdf = new \Mpdf\Mpdf([
'mode' => 'utf-8',
'format' => 'A4', //横向A4
'debug' => true,
//'tabSpaces' => 4,
//'ignore_invalid_utf8' => true,
'orientation' => '', //横向
"autoScriptToLang"=>true, //自动适配语言（支持中文）
"autoLangToFont"=>true, //自动选字体
"default_font_size"=>10, //默认字号px
"default_font"=>'simsun', //自定义字体，这个后面讲解
//"tempDir"=>$tempDir, //缓存目录
'margin_top' => 0, //上边距
'margin_left' => 7, //左边距
'margin_right' => 7, //右边距
//'mirrorMargins' => true,
"setAutoTopMargin"=>"stretch", //自动适应顶边距
//"setAutoBottomMargin"=>"stretch",
"autoMarginPadding"=>0 //边距和pad
]);

$mpdf -> WriteHTML($html, \Mpdf\HTMLParserMode::HTML_BODY);
$path = ROOT_PATH . 'public/template/pdf/';
$mpdf -> output($path . "{$fileName}.pdf");
}
}

/**
* 返回指定字符串之间的内容
*/
function getBetweenStr($str, $start, $end){
return substr($str, strlen($start) + strpos($str, $start), (strlen($str) - strpos($str, $end)) * (-1));
}

/**
* 图片转base64
*/
function fileToBase64($file){
$base64_file = '';
if(file_exists($file)){
$mime_type= mime_content_type($file);
$base64_data = base64_encode(file_get_contents($file));
$base64_file = 'data:'.$mime_type.';base64,'.$base64_data;
}
return $base64_file;
}

/**
* 获取url文件名
* @param	string	$str	文件路径(如：http://image.fa-zai.com/34-2.pdf)
*/
function splitFileName($str){
$strArr = explode('/',$str);
return preg_replace('/^[^\-]*\-/is', '', end($strArr)); //去除文档'-'前面的数字串
}

/**
* 对象转数组
*/
function objectToArray($object) {
$object =  json_decode( json_encode( $object ), true );
return  $object;
}

/**
* 递归返回数组,用于分类、菜单、城市等多级显示功能
* @param $table
* @param string $p_id
* @return array
*/
function tree($table,$p_id = '0') {
$tree = array();
foreach($table as $row){//遍历数据集里面的数据
if($row['ParentID'] == $p_id){
$tmp = $this -> tree($table,$row['SysID']);
if($tmp){
$row['children'] = $tmp;
}else{
$row['leaf'] = true;
}
$tree[] = $row;
}
}
return $tree;
}

/**
* 生成13位时间戳
*/
function getUnixTimestamp (){
list($s1, $s2) = explode(' ', microtime());
return (float)sprintf('%.0f',(floatval($s1) + floatval($s2)) * 1000);
}

/**
* 数组转XML编码
* @param mixed $data 数据
* @return string
*/
function arrayToXml2($array = []) {
$xml = '<xml>';
foreach ($array as $key => $val) {

$xml .= "<" . $key . ">" . $val . "</" . $key . ">";

}
$xml .= '</xml>';
return $xml;
}

/**
* 数组转XML编码
* @param mixed $data 数据
* @return string
*/
function arrayToXml($array = []) {
$xml = '<xml>';
foreach ($array as $key => $val) {
if(is_numeric($val)){
$xml .= "<" . $key . ">" . $val . "</" . $key . ">";
}else{
$xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
}
}
$xml .= '</xml>';
return $xml;
}

/**
* 数组转键值对格式key=value&key=value
*/
function formUrlencoded($data){
$str = '';
$len = count($data);
$num = 0;
foreach ($data as $key => $value) {
$num++;
$str = $str . $key . '=' . $value ;
if($num < $len) $str .= '&';
}
return $str;
}

/**
* 获取IP
*/
function getIP(){
$ip = request() -> ip();
return empty($ip) ? '0.0.0.0' : $ip;
}

/**
* 打印函数
* @param	array	$arr	数据源
*/
function p($arr){
echo '<pre>';
print_r($arr);
echo '</pre>';
}

/**
* 返回请求结果
* @param	array	$array		返回的数组
*/
function returnResults($array){
if(!isset($array['msg'])) $array['msg'] = controller("service/Error") -> searchCode($array['code']);
if( $array['code'] == '1' ) $array['success'] = true;
//  header('content-type:json; charset=utf-8');
echo json_encode($array, JSON_UNESCAPED_UNICODE);die;
}
/**
* 返回请求结果
* @param	array	$array		返回的数组
*/
function returnResults2($code = '', $msg = ''){
	$array['code'] = $code;
	$array['msg'] = $msg;
	if( $array['code'] == '1' ) $array['success'] = true;
	echo json_encode($array, JSON_UNESCAPED_UNICODE);die;
}

/**
* 验证参数是否为空
* @param	array	$array		要处理的KEY(数组)
* @param	array	$arr		原始数据(数组)
* @return	bool
*/
function is_empty($array, $arr){
for($i = 0; $i < count($array); $i++){
if(!isset($arr[$array[$i]]) || $arr[$array[$i]] === "" || (is_array($arr[$array[$i]]) && count($arr[$array[$i]]) == 0) ){
//      	var_dump($array[$i]);die;
returnResults(['code'=>-1, 'msg'=>'【' . $array[$i] . '】字段为空或不存在']);
return true;
}
}
return false;
}

/**
* 过滤空数据和相同数据
* @param	array	$arr		需要校验的(一维数组)
* @param	array	$title		需要校验的键名(一维数组)
* @param	array	$oldArr		原数组,可为空数组(一维数组)
* @param	array	$passEmpty	跳过检测为空的数组,可为空数组(一维数组)
*/
function filterArr($arr, $title, $oldArr, $passEmpty = []){
for( $i = 0; $i < count($title); $i++ ){
//		if($title[$i] == 'indictment_json'){
//			p($oldArr[$title[$i]]);
//			p($arr[$title[$i]]);
//      	var_dump($title[$i]);die;
//		}
if( (!in_array($title[$i], $passEmpty) && $arr[$title[$i]] == "") || (isset($oldArr[$title[$i]]) && $arr[$title[$i]] == $oldArr[$title[$i]]) ){
unset($arr[$title[$i]]);
}
}
return $arr;
}

/**
* 发送put请求
* @param string $url
* @param string $param
* @return bool|mixed
*/
function requestPut($url = '', $param = '', $header = ''){
if (empty($url)) {
return false;
}

$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL, $url); //设置put到的url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //返回字符串,而不直接输出
if(!is_null($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证对等证书
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //不检查服务器SSL证书

curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);//设置提交的字符串

$res = curl_exec($ch);
curl_close($ch);//关闭
return $res;
}

/**
* 发送post请求
* @param string $url
* @param string $param
* @return bool|mixed
*/
function requestPost($url = '', $param = '', $header = null, $cert = false)
{
if (empty($url)) {
return false;
}

$postUrl = $url;
$curlPost = $param;
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上

if(!is_null($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}

curl_setopt( $ch, CURLINFO_HEADER_OUT, true );

if( $cert == false ){
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
}else{
	curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLCERT, '/www/wwwroot/test.guokefuwu.com/public/cert/apiclient_cert.pem');
            curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
            curl_setopt($ch, CURLOPT_SSLKEY, '/www/wwwroot/test.guokefuwu.com/public/cert/apiclient_key.pem');
}
curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);

$data = curl_exec($ch); //运行curl
//  p(curl_getinfo($ch));

curl_close($ch);

return $data;
}

/**
* 发送get请求
* @param string 		$url
* @param string|array	$header
* @return bool|mixed
*/
function requestGet($url, $header = ['Accept: application/json']){

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);	//设置抓取的url
curl_setopt($curl, CURLOPT_HEADER, 0);	//设置头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_TIMEOUT, 1);	//超时设置,以秒为单位

// curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);	//超时设置，以毫秒为单位

curl_setopt($curl, CURLOPT_HTTPHEADER, $header);	//设置请求头
//设置获取的信息以文件流的形式返回，而不是直接输出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($curl);	//运行curl
curl_close($curl);
return $data;
}
